import time
from math import sqrt

def read_file():
	f = None
	try:
		myfile = open('myfile.txt', 'r')
		print(type(myfile))
		print(myfile.read())
	except FileNotFoundError:
		print('无法打开指定的文件!')
	except LookupError:
		print("指定了位置的编码！")
	except UnicodeDecodeError:
		pritn("读取文件时解码错误！")
	finally:
		if f:
			f.close()

# 用with关键字指定文件对象的上下文环境并在离开上下文时自动释放文件资源
def read_file2():
	print('======方式一======')
	#一次性读取整个文件内容
	with open('myfile.txt', 'r', encoding ='utf-8') as f:
		print(type(f))
		print(f.read())

	print('======方式二======')
	# 通过for-in循环逐行读取
	with open('myfile.txt', mode ='r') as f:
		for line in f:
			print(line,end = '')
			time.sleep(0.5)
	print()

	print('======方式三======')
	# 读取文件按行读取到列表中
	with open('myfile.txt') as f:
		lines = f.readlines()
	print(lines)


def is_prime(n):
	"判断素数的函数"
	assert n>0
	for factor in range(2,int(sqrt(n))+1):
		if n%factor == 0:
			return False
	return True if n!= 1 else False

def write_file():
	filenames = ('a.txt','b.txt','c.txt')
	fs_list = []
	try:
		for filename in filenames:
			fs_list.append(open(filename,'w',encoding = 'utf-8'))
		for number in range(1,10000):
			if is_prime(number):
				if number < 100:
					fs_list[0].write(str(number) + '\n')
				elif number < 1000:
					fs_list[1].write(str(number) + '\n')
				else:
					fs_list[2].write(str(number) + '\n')
	except IOError as ex:
		print(ex)
		print("写文件发生错误")
	finally:
		for fs in fs_list:
			fs.close()
	print('操作完成！')
if __name__ == '__main__':
	read_file()
	read_file2()
	write_file()